﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Text;
using Common;

public partial class insurance_orderutility : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Expires = -1;

        switch (RequestBase.GetFormString("otype"))
        {
            case "getenumitemsddl":
                LoadEnumItemsDDL();
                break;
            case "getenumitemsddlbygroupcode":
                LoadEnumItemsDDLByGroupCode();
                break; 
            case "getinsuranceproductlist":
                LoadInsuranceProductList();
                break;
            case "getinsuranceproductlistbyareacode":
                LoadInsuranceProductListByAreaCode();
                break; 
            case "getpolicytype":
                LoadPolicyTypeList();
                break;
            case "getproductitems":
                GetInsuranceProductItems();
                break;
            case "validateuserstate":
                if (String.IsNullOrEmpty(this.User.Identity.Name))
                    BLL.AjaxHelper.ResponseWrite("succeeded");
                else
                    BLL.AjaxHelper.ResponseWrite("unlogin");
                break;
            case "val_age": 
                // 验证被保人年龄 年龄应该大于3岁小于70岁 
                BLL.AjaxHelper.ResponseWrite(BLL.Insurance.ValidateHandle.ValAge(RequestBase.GetFormString("date")));
                break; 
            case "get_age":
                if (Utils.IsDateString(RequestBase.GetFormString("date")))
                    BLL.AjaxHelper.ResponseWrite((DateTime.Now.Year - DateTime.Parse(RequestBase.GetFormString("date")).Year).ToString());
                else
                    BLL.AjaxHelper.ResponseWrite("日期格式错误！");
                break; 
            case "val_effect_date":
                // 验证承保生效时间是否正确  
                BLL.AjaxHelper.ResponseWrite(BLL.Insurance.ValidateHandle.ValEffectDate(RequestBase.GetFormString("effectdate")));
                break;
            case "build_enddate":
                string res = "";
                // 计算保险止期
                string enddate = BLL.Insurance.ValidateHandle.BuildEndDate(RequestBase.GetFormString("effectdate"), RequestBase.GetFormString("productitemid"), out res);
                if (res == "succeeded")
                    BLL.AjaxHelper.ResponseWrite("succeeded|" + enddate);
                else
                    BLL.AjaxHelper.ResponseWrite(res);
                break;
            case "loadingorderilist":
                LoadingOrderList();
                break;
        }
    }
    #region 目的地
    void LoadEnumItemsDDL()
    {
        StringBuilder selOptions = new StringBuilder();
        string items = "<option value=\"{0}\">{1}</option>";

        DataTable dat = BLL.Search.CommonSearch.ExecSelect("EnumItem",
                          new string[] { "EnumText, EnumValue" },
                          new string[] { "EnumKey" },
                          new string[] { "Equal" },
                          new string[] { "'" + RequestBase.GetFormString("enumkey") + "'" },
                          new string[] { "SortIndex" },
                          new string[] { "ASC" });

        selOptions.Append(string.Format(items, "", "-- 请选择 --"));
        foreach (DataRow dr in dat.Select(""))
        {
            selOptions.Append(string.Format(items, dr["EnumValue"].ToString(), dr["EnumText"].ToString()));
        }

        dat.Dispose();
        BLL.AjaxHelper.ResponseWrite(selOptions.ToString());
    }
    void LoadEnumItemsDDLByGroupCode()
    {
        StringBuilder selOptions = new StringBuilder();
        string items = "<option value=\"{0}\">{1}</option>";

        DataTable dat = BLL.Search.CommonSearch.ExecSelect("EnumItem",
                          new string[] { "EnumText, EnumValue" },
                          new string[] { "EnumKey", "GroupCode" },
                          new string[] { "Equal", "Equal" },
                          new string[] { "'" + RequestBase.GetFormString("enumkey") + "'", RequestBase.GetFormString("groupcode") },
                          new string[] { "SortIndex" },
                          new string[] { "ASC" });

        selOptions.Append(string.Format(items, "", "-- 请选择 --"));
        foreach (DataRow dr in dat.Select(""))
        {
            selOptions.Append(string.Format(items, dr["EnumValue"].ToString(), dr["EnumText"].ToString()));
        }

        dat.Dispose();
        BLL.AjaxHelper.ResponseWrite(selOptions.ToString());
    }
    #endregion
    #region 签证类型
    void LoadPolicyTypeList()
    {
        StringBuilder selOptions = new StringBuilder();
        string items = "<option value=\"{0}\">{1}</option>";

        DataTable dat = BLL.Search.CommonSearch.ExecSelect("EnumItem",
                          new string[] { "EnumText, EnumValue" },
                          new string[] { "EnumKey" },
                          new string[] { "Equal" },
                          new string[] { "'CJType'" },
                          new string[] { "SortIndex" },
                          new string[] { "ASC" });

        selOptions.Append(string.Format(items, "", "-- 请选择 --"));
        foreach (DataRow dr in dat.Select(""))
        {
            selOptions.Append(string.Format(items, dr["EnumValue"].ToString(), dr["EnumText"].ToString()));
        }

        dat.Dispose();
        BLL.AjaxHelper.ResponseWrite(selOptions.ToString());
    }
    #endregion
    #region 产品
    void LoadInsuranceProductList()
    {
        StringBuilder selOptions = new StringBuilder();
        string items = "<option value=\"{0}\">{1}</option>";

        DataTable dat = BLL.Search.CommonSearch.ExecSelect("InsuranceProductBase",
                          new string[] { "ProductName, ProductId" },
                          new string[] { "StatusCode", "Layer", "DeletionStateCode", "ParentId" },
                          new string[] { "Equal", "Equal", "Equal", "Equal" },
                          new string[] { "0", "2", "0", "'574EE5AC-5FE0-49CD-82AF-B42886F65AE4'" },
                          new string[] { "LineNum" },
                          new string[] { "ASC" });

        selOptions.Append(string.Format(items, "", "-- 请选择 --"));
        foreach (DataRow dr in dat.Select(""))
        {
            selOptions.Append(string.Format(items, dr["ProductId"].ToString(), dr["ProductName"].ToString()));
        }

        dat.Dispose();
        BLL.AjaxHelper.ResponseWrite(selOptions.ToString());
    }
    void LoadInsuranceProductListByAreaCode()
    {
        StringBuilder selOptions = new StringBuilder();
        string items = "<option value=\"{0}\">{1}</option>";

        DataTable dat = BLL.Search.CommonSearch.ExecSelect("InsuranceProductBase",
                          new string[] { "ProductName, ProductId" },
                          new string[] { "StatusCode", "Layer", "DeletionStateCode", "ParentId", "AreaCodeList" },
                          new string[] { "Equal", "Equal", "Equal", "Equal", "Like" },
                          new string[] { "0", "2", "0", "'574EE5AC-5FE0-49CD-82AF-B42886F65AE4'", RequestBase.GetFormString("groupcode") },
                          new string[] { "LineNum" },
                          new string[] { "ASC" });

        selOptions.Append(string.Format(items, "", "-- 请选择 --"));
        foreach (DataRow dr in dat.Select(""))
        {
            selOptions.Append(string.Format(items, dr["ProductId"].ToString(), dr["ProductName"].ToString()));
        }

        dat.Dispose();
        BLL.AjaxHelper.ResponseWrite(selOptions.ToString());
    }
    /// <summary>
    /// 获取产品明细
    /// </summary>
    void GetInsuranceProductItems()
    {
        string productid = RequestBase.GetFormString("productid");
        StringBuilder _liHTML = new StringBuilder();
        string _li = "<option value=\"{0}\" price=\"{2}\" days=\"{3}\">{1}</option>";
        if (Utils.IsGuid(productid))
        {
            DataTable dt = BLL.CommonBLL.Select("InsuranceProductItemBase", "*", " AND ProductId='" + productid + "' AND DeletionStateCode=0 AND StatusCode=0 Order By ProtectedDays ASC ");
            foreach (DataRow dr in dt.Select(""))
            {
                _liHTML.Append(string.Format(_li, dr["ProductItemId"].ToString(), dr["ProtectedDays"].ToString() + " 天", string.Format("{0:f2}", decimal.Parse(dr["SalesPrice"].ToString())), dr["ProtectedDays"].ToString()));
            }
            dt.Clear();
            dt.Dispose();
        }
        BLL.AjaxHelper.ResponseWrite(_liHTML.ToString());
    }
    #endregion

    #region 订单管理
    void LoadingOrderList()
    {
        try
        {
            string ctrl = "~/_controls/ctlCartItems.ascx";
            Control uc_rep = LoadControl(ctrl);
            Repeater rptOrderManageList = (Repeater)uc_rep.FindControl("rptInsuranceOrderList");

            StringBuilder SQL = new StringBuilder();
            SQL.AppendFormat(" AND CustomerId = '{0}'", new MemberPageBase().UserId);

            if (RequestBase.GetFormString("querytext") != "" && !FilterHandler.ExistBadWord(RequestBase.GetFormString("querytext")) && Utils.IsSafeSqlString(RequestBase.GetFormString("querytext")))
            {
                SQL.Append(" AND (OrderNumber LIKE '%" + RequestBase.GetFormString("querytext") + "%')");
            }
            if (RequestBase.GetFormString("status") != "")
            {
                SQL.AppendFormat(" AND StatusCode = {0}", RequestBase.GetFormString("status"));
            }

            DBUtility.Pagination pagination = new DBUtility.Pagination();
            /// 页码
            if (RequestBase.GetFormString("page") != "" && Utils.IsNumber(RequestBase.GetFormString("page")))
                pagination.Sequence = Convert.ToInt32(RequestBase.GetFormString("page"));
            else
                pagination.Sequence = 1;

            if (RequestBase.GetFormString("upcount") != "" && Utils.IsNumber(RequestBase.GetFormString("upcount")))
                pagination.PageUpCount = Convert.ToInt32(RequestBase.GetFormString("upcount"));

            if (RequestBase.GetFormString("direction") == "next")
                pagination.Direction = "next";
            else
                pagination.Direction = "prev";

            pagination.PageBarCount = 8;
            pagination.PageSize = 12;
            pagination.Primarykey = "InsurancePolicyId";
            pagination.SearchField = "*";
            pagination.TableName = "vw_InsurancePolicyBaseForList";
            pagination.ItemUnit = "条记录";
            pagination.SearchSentence = SQL.ToString();
            pagination.SortSentence = " ORDER BY OrderNumber DESC";

            rptOrderManageList.DataSource = pagination.GetDataTable();
            rptOrderManageList.DataBind();

            pagination.GoNumeberPageBarCn3Asyn();
            uc_rep.GetType().GetProperty("PaginationBar").SetValue(uc_rep, pagination.PageBar, null);

            StringBuilder strb = new StringBuilder();
            StringWriter sw = new StringWriter(strb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            rptOrderManageList.RenderControl(htw);

            BLL.AjaxHelper.ResponseWrite(strb.ToString());
        }
        catch (System.Threading.ThreadAbortException err)
        {
            //nothing   to   do   
        }
        catch (Exception err)
        {
            BLL.AjaxHelper.ResponseWrite(err.Message);
        }
    } 
    #endregion
}